{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "共查找出 1185 条数据\n"
     ]
    }
   ],
   "source": [
    "import pymysql\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "# 定义接受的数据格式\n",
    "class FootballData:\n",
    "    def __init__(self,id,r,h,v,y,kd,kl,kw,od,ol,ow,rr):\n",
    "        self.id = id\n",
    "        self.r = r\n",
    "        self.h = h\n",
    "        self.v = v\n",
    "        self.y = y\n",
    "        self.kd = kd\n",
    "        self.kl = kl\n",
    "        self.kw = kw\n",
    "        self.od = od\n",
    "        self.ol = ol\n",
    "        self.ow = ow\n",
    "        self.rr = rr\n",
    "# 连接数据库\n",
    "connect = pymysql.Connect(host=\"localhost\",port=3306,user=\"root\",password=\"root\",database=\"football_lottery\",charset=\"utf8\")\n",
    "# 获取游标\n",
    "cursor = connect.cursor()\n",
    "# 查询数据  \n",
    "sql = \"SELECT\\\n",
    "\tg.id,\\\n",
    "\tg.race r,\\\n",
    "\tg.home_team h,\\\n",
    "\tg.visiting_team v,\\\n",
    "\tg.result y,\\\n",
    "\to.init_kelly_draw kd,\\\n",
    "\to.init_kelly_lose kl,\\\n",
    "\to.init_kelly_win kw,\\\n",
    "\to.init_odds_draw od,\\\n",
    "\to.init_odds_lose ol,\\\n",
    "\to.init_odds_win ow,\\\n",
    "\to.return_rate rr\\\n",
    " FROM\\\n",
    "\tgame_basic_info g\\\n",
    " INNER JOIN odds o ON o.game_info_id = g.id\"\n",
    "cursor.execute(sql)\n",
    "sdata = np.array([FootballData(id=row[0],r=row[1],h=row[2],v=row[3],y=row[4],kd=row[5],kl=row[6],kw=row[7],od=row[8],ol=row[9],ow=row[10],rr=row[11]) for row in cursor.fetchall()])\n",
    "#for row in cursor.fetchall():\n",
    "#    football = FootballData(id=row[0],r=row[1],h=row[2],v=row[3],y=row[4],kd=row[5],kl=row[6],kw=row[7],od=row[8],ol=row[9],ow=row[10],rr=row[11])\n",
    "print('共查找出', cursor.rowcount, '条数据')  \n",
    "# 关闭连接  \n",
    "cursor.close()  \n",
    "connect.close()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 切分数据集\n",
    "def splitData(*data):\n",
    "     # 训练用\n",
    "    data_train = []\n",
    "     # 测试用\n",
    "    data_validation = []\n",
    "    # 检验用\n",
    "    data_test = []\n",
    "    if(len(data)<2 or data[1] is None):\n",
    "        # 默认比例\n",
    "        rate = \"0.8;0.1;0.1\"\n",
    "    else: rate = data[1]\n",
    "    rate = rate.split(\";\")\n",
    "    rate = [ float(n) for n in rate]\n",
    "    # 分成 默认 三份数数据 0.8;0.1;0.1\n",
    "    d_len = len(data[0])\n",
    "    t_len = (int)(d_len * rate[0])\n",
    "    v_len = (int)(d_len * rate[1])\n",
    "    test_len = d_len - t_len - v_len\n",
    "    d_dict = {0:0,1:0,2:0}\n",
    "    for i in range(d_len):\n",
    "        r = -1\n",
    "        while(r == -1 or r ==3):\n",
    "            r = np.random.randint(0,3)\n",
    "            if(r== 0 and d_dict[r]<t_len):\n",
    "                # 训练用\n",
    "                data_train.append(data[0][i])\n",
    "                d_dict[r] += 1\n",
    "            elif(r==1 and d_dict[r]<v_len):\n",
    "                # 测试用\n",
    "                data_validation.append(data[0][i])\n",
    "                d_dict[r] += 1\n",
    "            elif(r==2 and d_dict[r]<test_len):\n",
    "                # 检验用\n",
    "                data_test.append(data[0][i])\n",
    "                d_dict[r] += 1\n",
    "            elif(d_dict[r]==t_len and d_dict[r]==test_len and d_dict[r]==test_len): r=3\n",
    "            else : r= -1\n",
    "    return data_train,data_validation,data_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def randdomData(data,size):\n",
    "    r_x = []\n",
    "    r_y = []\n",
    "    if(len(data)<size):size = len(data)\n",
    "    else:size = size\n",
    "    exitIn = []\n",
    "    for i in range(size):\n",
    "        index = np.random.randint(0,len(data))\n",
    "        while(index in exitIn):\n",
    "            index = np.random.randint(0,len(data))\n",
    "        obj = data[index]\n",
    "        r_y.append(obj.y)\n",
    "        #r_x.append([obj.r,obj.h,obj.v,obj.kd,obj.kl,obj.kw,obj.od,obj.ol,obj.ow,obj.rr])\n",
    "        r_x.append([obj.kd,obj.kl,obj.kw,obj.od,obj.ol,obj.ow,obj.rr])\n",
    "    return r_x,r_y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess = tf.InteractiveSession()\n",
    "t_d,v_d,ts_d = splitData(sdata)\n",
    "x = tf.placeholder(\"float\",[None,7])\n",
    "w = tf.Variable(tf.zeros([7,10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "y = tf.nn.softmax(tf.matmul(x,w) + b)\n",
    "y_ = tf.placeholder(\"float\",[None])\n",
    "cross_entropy = - tf.reduce_sum(y_*tf.log(y))\n",
    "train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-5-38d5d0936da5>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-5-38d5d0936da5>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    with sess = tf.Session():\u001b[0m\n\u001b[1;37m              ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "with sess = tf.Session():\n",
    "    sess.run(init)\n",
    "    for i in range(1000):\n",
    "        batch_xs,batch_ys =randdomData(t_d,10)\n",
    "        sess.run(train_step,feed_dict={x: batch_xs,y_:batch_ys})\n",
    "    correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_min(y_,1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n",
    "    t_xs,t_ys =randdomData(ts_d,1000)\n",
    "    print(sess.run(accuracy,feed_dict={x: t_xs, y_: t_ys}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
